<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="./Stack_Queue.js"></script>
    <script>
        /***
         *  队列实现栈
         *      队列顺序进来顺序出去。
         *      怎么逆序实现栈呢？
         *      pop 每次返回队列的最后一个元素
         *      而队列的poll方法每次弹出队列的第一个元素
         *  ===》 每次pop的时候，依次弹出除了最后一个元素外的其他元素
         *        help队列暂存弹出的元素
         *        之后再交换help 和原本队列 （即help是每次作用时的一次性暂存区
         */ 

         function TwoQueuesStack(){
            let queue = new Queue();
            let help = new Queue();

            this.push = function(value){
                queue.push(value);
                console.log(queue)
            }

            this.peek = function(){
                if(queue.empty()){
                    throw new Error("Stack is empty!");
                }
                // 将队列的前n-1个倒腾到help中
                while(queue.size!=1){
                    help.push(queue.poll())
                }
                let res = queue.poll();
                help.push(res);
                this.swap();
                return res;
            }
            this.pop = function(){
                if(queue.empty()){
                    throw new Error("Stack is empty!");
                }
                // 将队列的前n-1个倒腾到help中
                while(queue.size!=1){
                    help.push(queue.poll())
                }

                let res = queue.poll();
                this.swap();
                return res;
            }
            this.swap = function(){
                let temp = queue;
                queue = help;
                help = temp;
            }
         }


         let stack = new TwoQueuesStack()
         stack.push(23)
         stack.push(232323)
         stack.pop()
         console.log(stack.peek())
    </script>
</body>
</html>
